/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sp2p.peerToPeer.servidor;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author anderson
 */
public class RegistrationServer implements Runnable, Serializable {

    public static int numeroDeServidores = 0;
//    private Map<String, List<File>> mapaPesquisas = new HashMap<String, List<File>>();
    public List<String> ipServidores = new ArrayList<String>();
    private static ServerSocket servidor;
    private static Socket clienteSocket;
    private ObjectOutputStream out;
    private ObjectInputStream in;

    public RegistrationServer() {
    }

    public RegistrationServer(Socket clienteSocket) {
        this.clienteSocket = clienteSocket;
    }

    @Override
    public void run() {
        try {
            servidor = new ServerSocket(1234);
            while (true) {
                System.out.println("[Servidor de REGISTROS operando na porta 1234...]");
                System.out.println("[Esperando conexao...]");
                clienteSocket = servidor.accept();

                out = new ObjectOutputStream(clienteSocket.getOutputStream());
                out.flush();

                in = new ObjectInputStream(clienteSocket.getInputStream());
                out.writeObject("Ola cliente....");
                Object ipCliente = in.readObject();//lendo o que o cliente mandou
                numeroDeServidores++;
                ipServidores.add(ipCliente.toString());
                System.out.println("Servidor de REGISTROS diz: "+ipServidores.size()+" servidor na rede");
                for (int i = 0; i < ipServidores.size(); i++) {
                    out.writeObject(ipServidores.get(i));
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        RegistrationServer r = new RegistrationServer();
        Thread t = new Thread(r);
        t.start();
    }
}
